


/********************************
*		Global Variables		*
*********************************/
gameRunning = false;
var WebPlayer;		//Object contening the old game params, instencied at the begining of a new game
gameLink = "";
var nextEmbushForced = false;
var timerStarted = false;
var countdownTimer = 0;
var countdown;
treasureState = new Array(true, true);


/************************************
*		jQuery Bootstrapping		*
*************************************/
$(document).ready(
function() {
	/* gameLink pattern: 
	[Race:Level:GoldPieces:Position:[Items]]
	Race: 0 Gnome
		  1 Draenei
		  2 Orc
		  3 Goblin
		  4 Dwarf
		  5 Elf
		  6 Troll
		  7 Human
	Position: 0 Entrance
			  1 Gnomes
			  2 Draenei
			  3 Orcs
			  4 Goblins
			  5 Dwarfs
			  6 Elves
			  7 Trolls
			  8 Humans
			  9 Minotaur
			  10 Treasure 1
			  11 Treasure 2
	Item pattern: ItemId@UseState|ItemId@UseState|...
				  0 Buttplug Armor
				  1 Pet
				  2 Larger bag
				  3 Fake cum
				  4 Skimpy outfit
				  5 Healing potion
				  6 Healing balm
				  7 Gag Armor
				  8 Gem
				  9 Nipple clamps
	*/

	//*** Mouserover effects for buttons ***//
	$(".button").mouseover(
	function() {
		if ($(this).hasClass('disabled') === false)
		{
			$(this).addClass("buttonHover");
		}
	});
	$(".button").mouseout(
	function() {
		if ($(this).hasClass('disabled') === false)
		{
			$(this).removeClass("buttonHover");
		}
	});
	
	//*** Mouserover effects for map items ***//
	$(".mapItem").mouseover(
	function() {
		if ($(this).hasClass('currentPosition') === false
		 && $(this).hasClass('reachable') === true)
		{
			$(this).css("border", "4px inset #0077A6");
		}
	});
	$(".mapItem").mouseout(
	function() {
		if ($(this).hasClass('currentPosition') === false
		 && $(this).hasClass('reachable') === true)
		{
			$(this).css("border", "");
		}
	});
	
	//*** Button events ***//
	$(".button").click(
	function ()
	{
		var trigger = this;
		if ($(trigger).hasClass('disabled') === false)
		{
			switch (this.id)
			{
				case "newGameButton":
					if (!gameRunning)
					{
						NewGame();
					}
					break;
				case "loadGameButton":
					var loadLink = prompt("Enter the value of last saved game");
					LoadGame(loadLink);	
					break;
				case "saveGameButton":
					if (gameRunning)
					{
						WebPlayer.updateGameLink();
						prompt("Copy and save this code, if you want to play later:", gameLink);
					}
					break;
				case "manualButton":
					MoveMenuBar("left");
					$("#manualPannel").css("display", "block");
					$("#gamePannel").css("display", "");
					break;
				case "closeManualButton":
					MoveMenuBar("center");
					if (gameRunning)
					{
						$("#gamePannel").css("display", "block");
					}
					$("#manualPannel").css("display", "");
					break;
				case "itemButton":
					break;
				case "itemshopButton":
					break;
				case "taskStartButton":
					$("#taskFinishedButton").css("display", "block");
					$("#taskStartButton").css("display", "none");
					StartTimer(countdownTimer);
					break;
				case "taskFinishedButton":
					$("#taskStartButton").css("display", "block");
					$("#taskFinishedButton").css("display", "none");
					TaskFinished();
					break;
				default:
					break;
			}
		}
	});
	
	//*** Map Item Events ***//
	$(".mapItem").click(
	function ()
	{
		var trigger = this;
		if ($(trigger).hasClass('reachable') === true)
		{
			var newField = parseInt(trigger.id.substring(7, trigger.id.length));
            WebPlayer.changePosition(newField);
			ShowCurrentPosition();
			ShowReachablePositions();
			if (WebPlayer.position != 10 && WebPlayer.position != 11 && WebPlayer.position != 0)
			{
				if (WebPlayer.position === 9 && WebPlayer.level <= 9)
				{
					alert("Your level is to low! You can't pass the minotaur! You loose 2 levels!");
					$("#mapItem10").removeClass("reachable");
					$("#mapItem11").removeClass("reachable");
					WebPlayer.level = (WebPlayer.level > 2) ? WebPlayer.level - 2 : 0;
				}
				var embush = getRandomInt(0, 9);
				if (embush <= 6 || nextEmbushForced == true)
				{
					nextEmbushForced = false;
					ShowTask();
				}
				else
				{
					alert("Lucky! No embush!");
					TaskFinished();
				}
			}
			else
			{
				if (WebPlayer.position === 10)
				{
					if (treasureState[0] === true)
					{
						alert("You found 15 gold pieces in the treasure!");
						WebPlayer.addGold(15);
						treasureState[0] = false;
						UpdateGoldPieces();
					}
					else
					{
						alert("This treasure is empty!");
					}
				}
				else if (WebPlayer.position === 11)
				{
					if (treasureState[1] === true)
					{
						alert("You found 3 items in the treasure!");
						treasureState[1] = false;
						// TODO : verify rules for this part :
						var roll1 = getRandomInt(0, 9);
						var roll2 = getRandomInt(0, 9);
						var roll3 = getRandomInt(0, 9);
						WebPlayer.addItem(ExistingItems[roll1]);
						WebPlayer.addItem(ExistingItems[roll2]);
						WebPlayer.addItem(ExistingItems[roll3]);
					}
					else
					{
						alert("This treasure is empty!");
					}
				}
				else
				{
					EntranceResetTreasuresTrigger();
				}
			}
		}
	});
});


/****************************
*		Browser Hooks		*
*****************************/
// Keybinding for <Enter> and <Space>
$(document).keydown(function(e){
	if ((e.keyCode == 13 || e.keyCode == 32) && timerStarted == true)
	{
		$("#taskStartButton").css("display", "block");
		$("#taskFinishedButton").css("display", "none");
		TaskFinished();
	}
	else if ((e.keyCode == 13 || e.keyCode == 32) && timerStarted == false)
	{
		$("#taskFinishedButton").css("display", "block");
		$("#taskStartButton").css("display", "none");
		StartTimer(countdownTimer);
	}});
	
// Disable scrolling
$(document).keydown(function(e){
	if (e.keyCode == 32)
	{
		e.preventDefault();
	}});
$(document).scroll(function(e){
	window.scrollTo(0,0);
	});

	
/****************************
*		JS Extensions		*
*****************************/
//*** Functions for proving and parsing ***//
function parseBool(str)
{
	return str == "true" ? true : false;
}

function isNumber (str) {
  return ! isNaN (str) && str != null && str.length != 0;
}

//*** return random integer ***//
function getRandomInt (min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

//*** emptying an array with .clear() method, used for backpack when loading game in Player ***//
Array.prototype.clear = function() {
  while (this.length > 0) {
    this.pop();
  }
};


//*** Finded inheritance pattern (currently unused but possibly useful for item handling) ***//
// definiting the base constructor for all classes, which will execute the final class prototype's initialize method if exists
var Class = function() {
    this.initialize && this.initialize.apply(this, arguments);
};
Class.extend = function(childPrototype) { // defining a static method 'extend'
    var parent = this;
    var child = function() { // the child constructor is a call to its parent's
        return parent.apply(this, arguments);
    };
    child.extend = parent.extend; // adding the extend method to the child class
    var Surrogate = function() {}; // surrogate "trick"
    Surrogate.prototype = parent.prototype;
    child.prototype = new Surrogate();
    for(var key in childPrototype){
        child.prototype[key] = childPrototype[key];
    }
    return child; // returning the child class
};
/* USAGE :
var Dog = Class.extend({
    initialize : function() { // initialize is called by constructor at instanciation.
  this.numberOfLegs = 4;
 },
    bark : function() { console.log("wouf wouf"); }
});
 
var Doberman = Dog.extend({
   growl : function() { console.log("aouwww"); }
});
 
var rufus = new Doberman();
// now play with it !
// seen in french at http://blog.xebia.fr/2013/06/10/javascript-retour-aux-bases-constructeur-prototype-et-heritage/
*/


